import SingleLinkedList from '@/sources/LinkedList/singleLinkList'
import { IStack } from "./types";

export default class Stack<T = number> implements IStack<T> {
    private sl: SingleLinkedList<T>
    constructor() {
        this.sl = new SingleLinkedList();
    }

    /**
     * 获取栈中元素的数量
     */
    size() {
        return this.sl.size();
    }

    /**
     * 判断栈是否为空
     */
    isEmpty() {
        return this.size() === 0;
    }

    /**
     * 入栈
     * @param element 
     */
    push(element: T) {
        this.sl.add(element)
    }

    /**
     * 出栈
     */
    pop() {
        if (this.isEmpty()) return undefined
        return this.sl.remove(this.size() - 1)
    }

    /**
     * 获取栈顶元素
     */
    top() {
        if (this.isEmpty()) return undefined
        return this.sl.get(this.size() - 1)!.value;
    }

    /**
     * 遍历栈
     * @param cb 
     */
    forEach(cb: (ele: T, i: number) => boolean) {
        this.sl.forEach((ele, i) => {
            cb(ele, i)
        })
    }

    /**
     * 清空栈
     */
    clear() {
        this.sl.clear();
    }
} 